<template>
  <div style="height:100%;">
    <div v-loading="loading" class="analysisContainer" style="height:calc(100%);">
      <div class="analysisChartGroup v-flex" style="overflow: hidden;">
        <div id="echart-analysis1C" class="analysis1C" style="height:calc(100%);" />
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import { parseTime } from '@/utils'
import { find1CLateralAnalysis } from '@/api/cms/data-statistics'
export default {
  name: 'Transverse1C',
  props: {
    params: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      alldata: [],
      loading: false,
      queryParams: {},
      analysisChart: null,
      paramSelects: [{
        name: '导高-相机',
        id: 'guideHeight1'
      }, {
        name: '拉出值-相机',
        id: 'staggers1'
      }, {
        name: '水平硬点',
        id: 'hardPoint'
      }, {
        name: '弓网接触力',
        id: 'stress'
      }, {
        name: '燃弧',
        id: 'arcing'
      }, {
        name: '接触网电压',
        id: 'pressure'
      }, {
        name: '导高-雷达',
        id: 'guideHeight2'
      }, {
        name: '拉出值-雷达',
        id: 'staggers2'
      }, {
        name: '支柱号',
        id: 'pillarNum'
      }],
      chartDatas: [{
        roadMark: [], // 横坐标-公里标-锚段
        guideHeight1: [], // 导高-相机
        staggers1: [], // 拉出值-相机
        hardPoint: [], // 水平硬点
        stress: [], // 弓网接触力
        arcing: [], // 燃弧
        pressure: [], // 接触网电压
        guideHeight2: [], // 导高-雷达
        staggers2: [], // 拉出值-雷达
        pillarNum: [] // 支柱号
      }, {
        roadMark: [], // 横坐标-公里标-锚段
        guideHeight1: [], // 导高-相机
        staggers1: [], // 拉出值-相机
        hardPoint: [], // 水平硬点
        stress: [], // 弓网接触力
        arcing: [], // 燃弧
        pressure: [], // 接触网电压
        guideHeight2: [], // 导高-雷达
        staggers2: [], // 拉出值-雷达
        pillarNum: [] // 支柱号
      }]
    }
  },
  watch: {

  },
  mounted() {
    // this.getC1DataByParams(this.queryParams)
    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        if (_this.analysisChart) {
          _this.analysisChart.resize()
        }
      })
    })
  },
  beforeDestroy() {
    if (!this.analysisChart) {
      return
    }
    this.analysisChart.dispose()
    this.analysisChart = null
  },
  methods: {
    setParams(val) {
      this.queryParams.paramId = val
      this.initAnalysisChart(this.sortBySelected(this.chartDatas))
    },
    getC1DataByParams(param) {
      this.queryParams = param
      this.loading = true
      var that = this
      find1CLateralAnalysis(param).then(response => {
        this.loading = false
        // console.log('c1图形数据', response)
        this.clearChartDatas()
        if (response.data) {
          const data1 = param.detectDate.split(',')[0]
          const data2 = param.detectDate.split(',')[1] || null
          that.alldata = response.data[data1]

          if (data2) {
            that.alldata = that.alldata.concat(response.data[data2])
          }
          that.alldata.sort((a, b) => a['roadMark'] > b['roadMark'] ? 1 : -1)
          that.alldata.forEach(item => {
            item.roadMark = that.formatRoad(item.roadMark)
            if (parseTime(item.detectDate, '{y}-{m}-{d}') === data1) {
              for (const key in this.chartDatas[0]) {
                if (key === 'roadMark') {
                  this.chartDatas[0][key].push(this.formatRoad(item[key]))
                } else {
                  this.chartDatas[0][key].push(item[key] || 0)
                }
              }
              for (const key in this.chartDatas[1]) {
                if (key === 'roadMark') {
                  this.chartDatas[1][key].push(this.formatRoad(item[key]))
                } else {
                  this.chartDatas[1][key].push(null)
                }
              }
            } else {
              for (const key in this.chartDatas[0]) {
                if (key === 'roadMark') {
                  this.chartDatas[0][key].push(this.formatRoad(item[key]))
                } else {
                  this.chartDatas[0][key].push(null)
                }
              }
              for (const key in this.chartDatas[1]) {
                if (key === 'roadMark') {
                  this.chartDatas[1][key].push(this.formatRoad(item[key]))
                } else {
                  this.chartDatas[1][key].push(item[key] || 0)
                }
              }
            }
          })
        }
        this.initAnalysisChart(this.sortBySelected(this.chartDatas))
      })
    },
    clearChartDatas() {
      for (const key in this.chartDatas[0]) {
        this.chartDatas[0][key] = []
        this.chartDatas[1][key] = []
      }
    },
    sortBySelected(datas) {
      // 数据按参数筛选
      const paramSelected = this.queryParams.paramId
      const data = [{}]
      if (datas[0][paramSelected]) {
        const name = this.paramSelects.filter(e => {
          return e.id === paramSelected
        })[0].name
        data[0][name] = datas[0][paramSelected]
      }
      data[0]['detectDate'] = this.queryParams.detectDate.split(',')[0]
      data[0]['roadMark'] = datas[0]['roadMark']
      if (this.queryParams.detectDate.split(',')[1]) {
        data.push({})
        if (datas[1][paramSelected]) {
          const name = this.paramSelects.filter(e => {
            return e.id === paramSelected
          })[0].name
          data[1][name] = datas[1][paramSelected]
        }
        data[1]['detectDate'] = this.queryParams.detectDate.split(',')[1]
        data[1]['roadMark'] = datas[1]['roadMark']
      }

      return data
    },
    initAnalysisChart(datas) {
      if (!this.analysisChart) {
        this.analysisChart = echarts.init(document.getElementById('echart-analysis1C'))
      }
      const titles = []
      const legend = []
      const xAxis = {
        type: 'category',
        axisLabel: {
          interval: 0, // 坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
          rotate: 28 // 调整数值改变倾斜的幅度（范围-90到90）
        },
        axisLine: {
          lineStyle: {
            color: 'black'
          }
        },
        boundaryGap: false,
        data: datas[0].roadMark
      }
      const yAxis = {
        type: 'value',
        boundaryGap: true,
        scale: true,
        splitLine: {
          show: false
        },
        axisLabel: {
          showMinLabel: false,
          showMaxLabel: false
        },
        axisLine: {
          lineStyle: {
            color: 'black'
          }
        }
      }
      const series = []
      for (const key in datas[0]) {
        if (key !== 'detectDate' && key !== 'roadMark') {
          titles.push({
            textAlign: 'left',
            text: key,
            left: 20,
            top: 30,
            textStyle: {
              fontSize: 12,
              color: 'black',
              fontWeight: 'normal'
            }
          })
        }
      }
      for (const item of datas) {
        legend.push(item.detectDate)
        for (const key in item) {
          if (key !== 'detectDate' && key !== 'roadMark') {
            series.push({
              name: item.detectDate,
              type: 'line',
              smooth: true,
              connectNulls: true,
              data: item[key]
            })
          }
        }
      }

      const option = {
        title: titles,
        grid: {
          left: '70',
          right: '40',
          bottom: '60'
        },
        legend: {
          data: legend
        },
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0,
          confine: true,
          bordeRadius: 4,
          borderWidth: 1,
          borderColor: '#333',
          backgroundColor: 'rgba(255,255,255,0.9)',
          textStyle: {
            fontSize: 12,
            color: 'black'
          }
        },
        axisPointer: {
          type: 'shadow',
          link: {
            xAxisIndex: 'all'
          }
        },
        xAxis: xAxis,
        yAxis: yAxis,
        series: series
      }
      this.analysisChart.setOption(option, true)
    },
    formatRoad(val) {
      if (!val) return ''
      let value = val.toString()
      if (value.startsWith('-')) {
        value = '-K' + value.slice(1).replace(/\./, '+')
      } else {
        value = 'K' + value.replace(/\./, '+')
      }
      if (value.includes('+')) {
        const int = value.slice(0, value.indexOf('+'))
        const decimal = value.slice(value.indexOf('+') + 1)
        value = int +
          '+' +
          (decimal.length <= 3 ? decimal + '0'.repeat(3 - decimal.length) : decimal.slice(0, 3)) +
          '.' +
          (decimal.length <= 3 ? '00' : decimal.slice(3, 6) + '0'.repeat(5 - decimal.length > 0 ? 5 - decimal.length : 0))
      } else {
        value = value + '+000.00'
      }
      return value
    }
  }
}
</script>

<style lang="scss" scoped>
.analysisContainer {
    overflow: auto;
    color: black;

    .form-button {
      float: none;
    }

    .analysisChartGroup {
      position: relative;
      z-index: 1;
      height: 100%;
    }

    .phwidth {
      display: inline-block;
      width: 150px;
    }

    .chartTitle {
      position: absolute;
      top: 40px;
      z-index: 5;
      width: 100%;
      font-size: 14px;
      font-weight: normal;
      line-height: 24px;
      text-align: center;

      span {
        cursor: pointer;
      }
    }
  }
.analysis1C{
  margin-bottom: 10px;
  height: 100%;
  width: 100%;
}
</style>
